package com.googlecode.perfectable.visuable.parse;

import java.util.Map;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

class ElementStructureBuilder {

	private final VisualStructureBuilder parent;

	private String elementName;
	private boolean hasGeneratedIdentifier = false;
	private ImmutableMap.Builder<String, String> attributesBuilder = ImmutableMap.builder();
	private ImmutableList.Builder<ElementStructure> childrenBuilder = ImmutableList.builder();
	private String raw = ""; // MARK constant

	public ElementStructureBuilder(VisualStructureBuilder parent, String elementName) {
		this.parent = parent;
		this.elementName = elementName;
	}

	public VisualStructureBuilder children() {
		return new VisualStructureBuilder(this);
	}

	public ElementStructureBuilder children(Iterable<ElementStructure> children) {
		this.childrenBuilder.addAll(children);
		return this;
	}

	public ElementStructureBuilder identified() {
		this.hasGeneratedIdentifier = true;
		return this;
	}

	public ElementStructureBuilder identified(String identifier) {
		return this.attribute(ElementStructure.IDENTIFIER_ATTRIBUTE_NAME, identifier);
	}

	public ElementStructureBuilder attribute(String name, String value) {
		if(ElementStructure.IDENTIFIER_ATTRIBUTE_NAME.equals(name) && this.hasGeneratedIdentifier) {
			this.hasGeneratedIdentifier = false;
		}
		this.attributesBuilder.put(name, value);
		return this;
	}

	public ElementStructureBuilder text(String text) {
		this.raw = text;
		return this;
	}

	public VisualStructureBuilder closeElement() {
		Map<String, String> attributes = this.attributesBuilder.build();
		Iterable<ElementStructure> children = this.childrenBuilder.build();
		ElementStructure structure = new ElementStructure(this.elementName, attributes, this.hasGeneratedIdentifier,
				this.raw,
				children);
		this.parent.add(structure);
		return this.parent;
	}

}